import AgoraRTC, { IAgoraRTCClient, IAgoraRTCRemoteUser } from 'agora-rtc-sdk-ng'
import { message } from 'ant-design-vue'
import { changeLivestreamLens, setLivestreamQuality, startLivestream, stopLivestream } from '../api/manage'
import { checkLiveChannel, getLiveToken } from '../api/live'
import { sessionStorage } from '@/utils/storage'
import { ILiveInfo, qualityType, qualityTypeKeys, videoInfoType, videoInfoTypeKeys } from '../types/device'

class UseLive {
  async onStart(live: any, { appId, channel, token }: { appId: string, channel: string, token: string }) {
    const client = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' })
    AgoraRTC.setLogLevel(4)
    client.setClientRole('audience', { level: 2 })
    console.log('create live:-----------------------', client)
    // 当远程用户发布流时订阅
    client.on('user-joined', async (user: IAgoraRTCRemoteUser) => {
      message.info(`user[${user.uid}] join`)
    })
    if (client.connectionState === 'DISCONNECTED') {
      client.join(appId, channel, token)
    }

    client.on('user-published', async (user: IAgoraRTCRemoteUser, mediaType: 'audio' | 'video') => {
      await client.subscribe(user, mediaType)
      live.status = true
      nextTick(() => {
        if (mediaType === 'video') {
          console.log('subscribe success')
          const remoteVideoTrack = user.videoTrack!
          remoteVideoTrack.play(document.getElementById(live.index) as HTMLElement)
        }
      })
    })

    client.on('user-unpublished', async (user: any) => {
      live.status = false
      message.info('离开直播')
    })

    client.on('exception', async (e: any) => {
      console.log(e)
    })
    const { data } = await checkLiveChannel({ channel: live.channel })
    if (data.used) {
      live.isOpen = true
      await startLivestream({
        url: 'url',
        video_id: live.index,
        url_type: 0,
        video_quality: 0,
        channel: live.channel
      }).then((res) => {
        if (res.code === 1) {
          message.success(res.message)
          console.log('start play livestream', res)
        }
      })
    }
    return client
  }

  async onStop(live: any): Promise<void> {
    live.client.leave()
  }

  async onSwitchCamera(livePara: ILiveInfo, dronePara: videoInfoTypeKeys): Promise<void> {
    await changeLivestreamLens({
      video_id: livePara.index,
      video_type: dronePara
    }).then((res) => {
      if (res.code === 1) {
        livePara.type = dronePara
        message.success(`切换镜头到${videoInfoType[dronePara]}成功`)
      }
    })
  }

  // 切换清晰度
  async onSwitchQuality(livePara: ILiveInfo, quality: qualityTypeKeys): Promise<void> {
    await setLivestreamQuality({
      video_id: livePara.index,
      video_quality: quality
    }).then((res) => {
      if (res.code === 1) {
        livePara.quality = quality
        message.success(`切换清晰度到${qualityType[quality]}成功`)
      }
    })
  }
}

export default new UseLive()
